import { Body, Controller, Ctx, Post } from "koa-ts-controllers"
import { RegisterBody } from "../validators/User"
import {User as UserModel} from "../models/User"
import Boom from "@hapi/boom"
import { Context } from "koa";

@Controller("/user")
export class UserController{

    // 用户注册
    @Post("/register")
    async register(
        @Ctx() ctx: Context,
        @Body() body:RegisterBody
    ){
        let {name, password} = body;

        // 验证用户是否已经注册
        let user = await UserModel.findOne({
            where:{
                name
            }
        })

        if(user){
            throw Boom.conflict("注册失败","用户名已经被注册") 
        }

        let newUser = new UserModel();
        newUser.name = name;
        newUser.password = password;


        console.log(newUser);
        
        await newUser.save();
        ctx.status = 201

        return {
            id: newUser.id,
            name: newUser.name,
            createAt: newUser.createAt
        }
    }
}